package test.excel.workbook;

import org.apache.poi.ss.usermodel.Workbook;

import test.excel.config.FileImportConfig;
import test.excel.config.SheetConfig;
import test.excel.dto.WorkbookDto;

public class WorkbookReader {
    private Workbook wb;

    private FileImportConfig config;

    public WorkbookReader(Workbook wb, FileImportConfig config) {
        this.wb = wb;
        this.config = config;
    }

    public WorkbookDto read() {
        try {
            WorkbookDto workbookDto = new WorkbookDto();

            for (SheetConfig sheetConfig : config.getSheets()) {
                workbookDto.getSheets().add(new SheetReader(wb.getSheetAt(getSheetIndex(sheetConfig)), sheetConfig).read());
            }

            return workbookDto;
        } catch (Exception e) {
            throw new IllegalStateException("Error parsing file: " + config.getName(), e);
        }
    }

    private int getSheetIndex(SheetConfig sheetConfig) {
        int sheetIndex;

        if (sheetConfig.getSheetName() == null) {
            sheetIndex = sheetConfig.getIndex();

            if (sheetIndex >= wb.getNumberOfSheets()) throw new IllegalStateException("Sheet index is " + sheetIndex + ", but number of sheets is " + wb.getNumberOfSheets());
        } else {
            sheetIndex = wb.getSheetIndex(sheetConfig.getSheetName());

            if (sheetIndex == -1) throw new IllegalStateException("Invalid sheet name.");
        }

        return sheetIndex;
    }
}
